import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

@WebServlet(urlPatterns = {"/uploadServlet"})
@MultipartConfig(location = "C:\\Users\\WHITE\\IdeaProjects\\tt\\JAVAEE-LAB2\\src\\main\\webapp\\images")
public class UploadServlet extends HttpServlet {
    @Override
    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        res.setContentType("text/html;charset=UTF-8");

        //表单验证
        if(req.getContentType()==null||!req.getContentType().startsWith("multipart/form-data")){
            res.getWriter().println("<script type=\"text/javascript\">\n" +
                    "        alert('http请求的ContentType必须为multipart/form-data')\n" +
                    "        window.history.back();\n" +
                    "         \n" +
                    "</script>");
            return;
        }

        //随着图片上传的，还有用户id，本地创建image文件夹，存放以用户id命名的图片
        String username=req.getParameter("userid");
        req.getParts().stream()
                .filter(part -> part.getName().equals("file"))
                .forEach(part -> {
                    //过滤掉不为文件的输入
                    String filename=part.getSubmittedFileName();
                    //判断上传文件是否合法
                    boolean flag=false;
                    String[] str = filename.split("\\.");
                    String[] pic = {"png", "jpg", "jpeg", "bmp", "tif"};
                    if(filename!=null) {
                        for (int i = 0; i < pic.length; i++) {
                            if (str[1].equals(pic[i]))
                                flag = true;
                        }
                    }

                    if(!flag) {
                        try {
                            res.getWriter().println("<script type=\"text/javascript\">\n" +
                                    "        alert('上传失败！')\n" +
                                    "        window.history.back();\n" +
                                    "         \n" +
                                    "</script>");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }else{
                        try {
                            //将文件写入本地文件夹，以用户id命名
                            part.write(username+"."+str[1]);
                            res.getWriter().println("<script type=\"text/javascript\">\n" +
                                    "        window.history.back();\n" +
                                    "         \n" +
                                    "</script>");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
}